<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta http-equiv="Content-Type" content="application/x-javascript; charset=utf-8"/>
<style>
  .page{
    width: 100% !important;
    text-align:center;
  }


</style>
<script src="../jquery-2.2.4.js"></script>
<script src="pdf.js"></script>
<script src="pdf.worker.js"></script>

<script>

//PDF.js插件定义的对象，给定pdf文件的URL或者一个Uint8Array数组，调用PDFJS.getDocument()可以获取
var pdfDoc = null;
var pdfData =''
//缩放比例
var scale = 1.5;
//pdf文件的总页数
var count = 1;

$(document).ready(function() {
    window.addEventListener("message",handleMessageFromParent)
});

function handleMessageFromParent(){
   var data = event.data;
    switch (data.cmd) {
      case 'returnInfo':
        pdfData=data.params.info;
        $("#pdfCache").text("");
        $("#pdfContainer").html("");
        $("#pdfCache").text(data.params.info);
          var data = char2buf(window.atob($("#pdfCache").text()));
          PDFJS.getDocument(data).then(function(pdfDoc_) {
            pdfDoc = pdfDoc_;
            count = pdfDoc.numPages;
            //绘制所有的页面
            renderAll();
            });
        break
    }
}




function renderAll(){
  for(var curPage=1;curPage<=count;curPage++){
    //新建一个<canvas>用于，并将对应页面的内容绘制到这个canvas上
    var canvas = document.createElement("canvas");
    var div = document.createElement("div");
    $(div).attr("id","page"+curPage);
    $(div).attr("class","page");
    $(canvas).attr("class","canvas");
    $(div).append(canvas);
    $("#pdfContainer").append(div);
    renderPage(curPage,canvas);
  }
}

function renderPage(num,canvas) {
  // Using promise to fetch the page
  pdfDoc.getPage(num).then(function(page) {
    var ctx = canvas.getContext('2d');
    var viewport = page.getViewport(scale);
    canvas.height = viewport.height;
    canvas.width = viewport.width;
    // Render PDF page into canvas context
    var renderContext = {
      canvasContext : ctx,
      viewport : viewport
    };
    var renderTask = page.render(renderContext);

    // Wait for rendering to finish
    renderTask.promise.then(function() {
        //这是每次绘制一页内容之后的回调函数
        console.log("Page"+num+" rendered");
    });
  });
}

function zoomOut(){
  scale+=0.4;
  $("#pdfContainer").empty();
  renderAll();
}

function zoomIn(){
  scale-=0.4;
  $("#pdfContainer").empty();
  renderAll();
}

/*string -> Unit8Array*/
function char2buf(str){
  var out = new ArrayBuffer(str.length);
  var u16a= new Uint8Array(out);
  var strs = str.split("");
  for(var i =0 ; i<strs.length;i++){
      u16a[i]=strs[i].charCodeAt();
  }
  return u16a;
}
function convertBase64ToBlob(base64, fileType, slice) {


  // 使用atob方法解码base64
  var raw = window.atob(base64);
  // 创建一个存储解码后数据的数组
  var uInt8Array = new Uint8Array(raw.length);
  // blob只能接收二进制编码，需要讲base64转为二进制再塞进去
  for (var i = 0; i < raw.length; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }
  // 这里给了一个返回值，在别的方法掉用传入base64编码就可以得到转化后的blob
  return new Blob([uInt8Array], { type: "application/pdf" });
}
function dowonladPdf() {
  const blob = convertBase64ToBlob(pdfData, 'application/pdf', 1024)
  if (navigator.msSaveBlob) {
    return navigator.msSaveBlob(blob, '分析报告.pdf');
  }
  const urlFromBlob = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = urlFromBlob;
  a.download ='分析报告.pdf';
  document.body.appendChild(a);
  a.click();
  window.URL.revokeObjectURL(urlFromBlob);
  document.body.removeChild(a)
}
</script>
<title>LoadPDF_fromArrayBuffer</title>
</head>
<div>
<div>
<!--<button onclick="zoomOut()">放大</button>
<button onclick="zoomIn()">缩小</button>-->
</div>
<div id="pdfContainer" style="width: 80%;text-align: center" ></div>
<div id=pdfCache style="display:none;width: 80%"></div>
</div>
</html>
